package TestDemo;

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

public class Main {

    public ListNode detectCycle(ListNode head) {
        if (head == null) return null;

        ListNode fast = head;
        ListNode slow = head;

        while (fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow){
                break;
            }
        }

        if (fast == null || fast.next == null) return null;
        slow = head;

        while (slow != fast){
            fast = fast.next;
            slow = slow.next;
        }

        return fast;
    }

    public boolean chkPalindrome(ListNode A) {
        // write code here
        if (A == null) return false;
        ListNode fast = A;
        ListNode slow = A;
        while (fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
        }
        ListNode cur = slow.next;
        while (cur != null){
            ListNode curNext = cur.next;
            cur.next = slow;
            slow = cur;
            cur = curNext;
        }
        while (A != slow){
            if (A.val != slow.val){
                return false;
            }
            if (A.next == slow){
                return true;
            }
            A = A.next;
            slow = slow.next;
        }
        return true;
    }

    public static void main(String[] args) {

    }

}
